package com.jswlw.service.helper;

import com.alibaba.fastjson.JSON;
import com.jswlw.common.BaseApiResponse;
import com.jswlw.common.BaseException;
import com.jswlw.common.ResponseStatus;
import com.jswlw.config.DefaultHttpClient;
import com.jswlw.controller.devapi.req.ProtocolMessage;
import com.jswlw.entity.biz.ApiFail;
import com.jswlw.service.biz.ApiFailService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * @author 吴维斌 E-mail:wuweibin0817@163.com
 * @version 创建时间：${date} ${time}
 */
@Slf4j
@Component
public class HttpHelper {

    @Autowired
    DefaultHttpClient defaultHttpClient;
    @Autowired
    ApiFailService apiFailService;

    public boolean post(String url, String json) {
        log.info("url:" + url);
        log.info("接口参数:" + json);
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(mediaType, json))
                .build();
        try {
            Response response = defaultHttpClient.newCall(request).execute();
            String resultStr = response.body().string();
            log.info("请求执行结果:" + resultStr);
            BaseApiResponse apiResponse = JSON.parseObject(resultStr, BaseApiResponse.class);
            if (!apiResponse.getCode().equals(0)) {

                log.info("请求执行失败:" + apiResponse.getMsg());
                Map protocolMessage = JSON.parseObject(json, Map.class);
                if (protocolMessage.get("cmd").equals(15)) {
                    return false;
                }
                ApiFail apiFail = new ApiFail();
                apiFail.setCmdType((int) protocolMessage.get("cmd"));
                apiFail.setIcCid(String.valueOf(protocolMessage.get("imei")));
                apiFail.setUrl(url);
                apiFail.setParams(json);
                apiFail.setCreateTime(new Date());
                apiFail.setFailCount(1);
                apiFail.setFailContent(JSON.toJSONString(apiResponse));
                apiFailService.add(apiFail);
                return false;
            }

            return true;
        } catch (Exception e) {
            log.error("发送请求异常:", e);
        }
        return false;
    }

    public String postResult(String url, String json) {
        log.info("url:" + url);
        log.info("接口参数:" + json);
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(mediaType, json))
                .build();
        try {
            Response response = defaultHttpClient.newCall(request).execute();
            String result = response.body().string();
            BaseApiResponse apiResponse = JSON.parseObject(result, BaseApiResponse.class);
            if (!apiResponse.getCode().equals(0)) {
                throw BaseException.of(ResponseStatus.BUSINESS_ERROR);
            }
            log.info("请求执行结果:" + JSON.toJSONString(apiResponse));

            return result;
        } catch (IOException e) {
            throw BaseException.of(ResponseStatus.BUSINESS_ERROR);
        }
    }

    public boolean post(ApiFail apiFail) {
        log.info("请求重试:" + JSON.toJSONString(apiFail));
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        Request request = new Request.Builder()
                .url(apiFail.getUrl())
                .post(RequestBody.create(mediaType, apiFail.getParams()))
                .build();
        try {
            Response response = defaultHttpClient.newCall(request).execute();
            BaseApiResponse apiResponse = JSON.parseObject(response.body().string(), BaseApiResponse.class);
            log.info("请求执行结果:" + JSON.toJSONString(apiResponse));
            if (!apiResponse.getCode().equals(0)) {
                apiFail.setFailContent(JSON.toJSONString(apiResponse));
                return false;
            }

            return true;
        } catch (Exception e) {
            log.error("发送请求异常:", e);
        }
        return false;
    }
}
